var debug=false;

var knownDates=[];
var available={};
var ratings={};
var vetos={};
var reasons={};
var attending=false;
var geekout=false;
var showVetoedDates=false;

function waveInit()
{
  if(wave)
  {
    //log('set callbacks');
    wave.setStateCallback(stateUpdated);
//    wave.ui.loadCss();
//    wave.ui.makeButton(getElementById('geekoutButton'));

    if(wave.getViewer()==wave.getHost())
    {
      $(".admin").show();
    }
  }
  else
  {
    log("no wave");
  }
}

function getValue(map, name, def)
{
  if(map==null)
  {
    return def;
  }
  else
  {
    value=map[name];
    if(value==null)
    {
      return def;
    }
    else
    {
      return value;
    }
  }
}

function addDate()
{
  $("#newDate").empty().append('<input id="newDateText" type="text"/><input type="submit" value="Add" onclick="doAdd()"/><input class="cancelAdd" type="submit" value="Cancel" onclick="cancelAdd"/>');
  $("#cancelAdd").click(cancelAdd);
  $("#newDateText").focus();
  return false;
}

function doAdd()
{
  var date=$("#newDateText").val();
  submitDate(date);
  cancelAdd();
}

function cancelAdd()
{
  $("#newDate").empty();
}

function checkAvailable()
{
  clear();
  log('checkAvailable');
  available={};
  $("#dates tr").each(function() {
    var date=$(this).children(".date").text();
    available[date]=$(this).children(".tdav").children(".available").is(":checked");
  });
  submitAvailable();
}

function submitAvailable()
{
  var viewer=wave.getViewer().getId();
  var state=wave.getState();

  var myState=JSON.parse(state.get(viewer, "{}"));
  myState['available']=available;

  var delta={};
  delta[viewer]=JSON.stringify(myState);

  state.submitDelta(delta);

  log('changed');
  log(JSON.stringify(delta));
}

function checkRatings()
{
  log('checkRatings');
  ratings={};
  $("#dates tr").each(function() {
    var date=$(this).children(".date").text();
    log(date);
    ratings[date]=$(this).children("td").children(".rating").filter(":checked").attr('value');
  });
  submitRatings();
}

function submitRatings()
{
  var viewer=wave.getViewer().getId();
  var state=wave.getState();

  var myState=JSON.parse(state.get(viewer, "{}"));
  myState['ratings']=ratings;

  var delta={};
  delta[viewer]=JSON.stringify(myState);

  state.submitDelta(delta);

  log('changed');
  log(JSON.stringify(delta));
}

function checkVetos()
{
  log('checkVetos');
  vetos={};
  $("#dates tr").each(function() {
    var date=$(this).children(".date").text();
    log(date);
    veto=$(this).children("td").children(".veto").attr('checked');
    if(veto==null)
    {
      veto=false;
    }
    vetos[date]=veto;
  });
  submitVetos();
}

function submitVetos()
{
  var viewer=wave.getViewer().getId();
  var state=wave.getState();

  var myState=JSON.parse(state.get(viewer, "{}"));
  myState['vetos']=vetos;

  var delta={};
  delta[viewer]=JSON.stringify(myState);

  state.submitDelta(delta);

  log('changed');
  log(JSON.stringify(delta));
}

function checkReasons()
{
  log('checkReasons');
  reasons={};
  $("#dates tr").each(function() {
    var date=$(this).children(".date").text();
    log(date);
    reason=$(this).children("td").children(".reason").val();
    if(reason==null)
    {
      reason='';
    }
    reasons[date]=reason;
  });
  submitReasons();
}

function submitReasons()
{
  var viewer=wave.getViewer().getId();
  var state=wave.getState();

  var myState=JSON.parse(state.get(viewer, "{}"));
  myState['reasons']=reasons;

  var delta={};
  delta[viewer]=JSON.stringify(myState);

  state.submitDelta(delta);

  log('changed');
  log(JSON.stringify(delta));
}

function checkAttending()
{
  log('checkAttending');
  attending=$(this).attr('value')=='true';
  submitAttending();
}

function submitAttending()
{
  var viewer=wave.getViewer().getId();
  var state=wave.getState();

  var myState=JSON.parse(state.get(viewer, "{}"));
  myState['attending']=attending;

  var delta={};
  delta[viewer]=JSON.stringify(myState);

  state.submitDelta(delta);

  log('changed');
  log(JSON.stringify(delta));
}

function encodeToHex(str){
    var r="";
    var e=str.length;
    var c=0;
    var h;
    while(c<e){
        h=str.charCodeAt(c++).toString(16);
        while(h.length<3) h="0"+h;
        r+=h;
    }
    return r;
}

function addEntry(date)
{
  if(date=='')
  {
    return;
  }

  if(!(date in oc(knownDates)))
  {
    log('addEntry');
    log(date);
    log(knownDates);
    var id=encodeToHex(date);
    var rid='result-'+encodeToHex(date);
    $("#entryTemplate").clone().attr('id', id).appendTo("#dates");
    $("#"+id).show();
    $("#"+id+" .date").text(date);
    $("#"+id+" td").children(".rating").attr('name', 'rating-'+id);
    $("#"+id+" td").children(".nr").attr('checked', true);
    $(".rating").click(checkRatings);
    $(".veto").click(checkVetos);
    $(".reason").blur(checkReasons);

    if(geekout)
    {
      $(".geekout").show();
    }
    else
    {
      $(".geekout").hide();
    }

    $("#resultTemplate").clone().attr('id', rid).appendTo("#resultDates");
    $("#"+rid).show();
    $("#"+rid+" .date").text(date);

    knownDates.push(date);
  }
}

function clear()
{
  $("#log").empty();
}

function log(text)
{
  if(typeof(console)==="undefined")
  {
    if(debug)
    {
      $("#log").append("<p>"+text+"</p>");
    }
  }
  else
  {
    console.log(text);
  }
}

function oc(arguments)
{
  var o = {};
  for(var i=0;i<arguments.length;i++)
  {
    o[arguments[i]]=null;
  }
  return o;
}

Array.prototype.findIndex = function(value)
{
  var ctr = "";
  for (var i=0; i < this.length; i++)
  {
    // use === to check for Matches. ie., identical (===), ;
    if (this[i] == value)
    {
      return i;
    }
  }

  return ctr;
};

function stateUpdated()
{
  log('updated');
  var newState=wave.getState();
  log(newState);

  var keys = newState.getKeys();
  for (var i = 0; i < keys.length; ++i)
  {
    var user = keys[i];
    var userState=JSON.parse(newState.get(user));

    log(JSON.stringify(userState));

    var userDates=getValue(userState, 'dates', []);
    log('userDates:');
    log(userDates);
    log(user);
    var userAvailable=getValue(userState, 'available', {});

    for (var j = 0; j < userDates.length; ++j)
    {
      addEntry(userDates[j]);
    }
  }

  var viewer=wave.getViewer().getId();
  var myState=JSON.parse(newState.get(viewer, "{}"));

  var at=myState['attending'];
  if(at==null || at==false)
  {
    $("#notattending").attr('checked', true);
  }
  else
  {
    $("#attending").attr('checked', true);
  }

  var avs=myState['available'];
  if(avs==null)
  {
   avs={};
  }

  var rs=myState['ratings'];
  if(rs==null)
  {
   rs={};
  }

  var vs=myState['vetos'];
  if(vs==null)
  {
   vs={};
  }

  var res=myState['reasons'];
  if(res==null)
  {
    res={};
  }

  $("#dates tr").each(function(index, item) {
    var date=$(item).children(".date").text();
    log(date);
    var avbox=$(item).children(".tdav").children(".available");
    var av=avs[date];
    if(av==null || av==false)
    {
      avbox.attr('checked', false);
    }
    else
    {
      avbox.attr('checked', true);
    }

    var vetobox=$(item).children("td").children(".veto");
    var reasonbox=$(item).children("td").children(".reason");
    var veto=vs[date];
    var reason=res[date];
    if(reason==null)
    {
      reason='';
    }

    if(veto==null || veto==false)
    {
      vetobox.attr('checked', false);
      reasonbox.val('');
      reasonbox.attr('disabled', true);
    }
    else
    {
      vetobox.attr('checked', true);
      reasonbox.attr('disabled', false);
      reasonbox.val(reason);
    }

    var id=encodeToHex(date);
    var r=rs[date];
    if(r==null)
    {
      r='nr';
    }

    log('r:');
    log(r);

    $('[name="rating-'+id+'"]').filter('[value="'+r+'"]').attr('checked', true);
    log($('[name="rating-'+id+'"]'));
  });

  updateMatrix();
  updateResults();
  updateSettings();
}

function sum(samples)
{
  if(samples==null || samples.length==0)
  {
    return 0;
  }

  var s=0;
  for(var x=0; x<samples.length; x++)
  {
    if(samples[x]!='nr')
    {
      s=s+samples[x];
    }
  }

  return s;
}

function len(samples)
{
  if(samples==null || samples.length==0)
  {
    return 0;
  }

  var s=0;
  for(var x=0; x<samples.length; x++)
  {
    if(samples[x]!='nr')
    {
      s=s+1;
    }
  }

  return s;
}

function average(samples)
{
  if(samples==null || samples.length==0)
  {
    return 0;
  }

  return sum(samples)/len(samples);
}

function maxima(samples)
{
  if(samples==null || samples.length==0)
  {
    return 0;
  }

  var max=0;
  for(var x=0; x<samples.length; x++)
  {
    if(samples[x]!='nr' && samples[x]>max)
    {
      max=samples[x];
    }
  }

  return max;
}

function maxpos(samples)
{
  if(samples==null || samples.length==0)
  {
    log('no samples');
    return -1;
  }

  var max=0;
  var posl=[];
  for(var x=0; x<samples.length; x++)
  {
    if(samples[x]!='nr')
    {
      if(samples[x]>max)
      {
        max=samples[x];
        posl=[x];
      }
      else if(samples[x]==max)
      {
        posl.push(x);
      }
    }
  }

  return posl;
}

function variance(samples)
{
  if(samples==null || samples.length==0)
  {
    return 0;
  }

  var avg=average(samples);

  var devs=[];
  for(var x=0; x<samples.length; x++)
  {
    if(samples[x]!='nr')
    {
      var dev=samples[x]-avg;
      devs.push(dev*dev);
    }
  }

  return sum(devs)/len(samples);
}

function veam(candidates, ratingMatrix, weights)
{
  log('veam candidates:');
  log(candidates);
  var scores=[];
  var means=[];
  for(var y=0; y<candidates.length; y++) // Zero out scores
  {
    scores.push(0);
  }

  for(var x=0; x<ratingMatrix[0].length; x++) // For each user
  {
    var scoreSum='nr';
    var scoreCount=0;

    for(var y=0; y<candidates.length; y++) // Add scores for each candidate
    {
      if(ratingMatrix[candidates[y]][x]!='nr')
      {
        scoreCount=scoreCount+1;
        if(scoreSum=='nr')
        {
          scoreSum=ratingMatrix[candidates[y]][x]*weights[candidates[y]];
        }
        else
        {
          scoreSum=scoreSum+(ratingMatrix[candidates[y]][x]*weights[candidates[y]]);
        }
      }
    }

    if(scoreSum=='nr')
    {
      means.push('nr');
    }
    else
    {
      means.push(scoreSum/scoreCount);
    }
  }

  for(var y=0; y<candidates.length; y++) // Add scores for each candidate
  {
    for(var x=0; x<means.length; x++)
    {
      if(means[x]!='nr' && ratingMatrix[candidates[y]][x]!='nr' && (ratingMatrix[candidates[y]][x]*weights[candidates[y]])>means[x])
      {
        log('point! '+means[x]+' < '+(ratingMatrix[candidates[y]][x]*weights[candidates[y]]));
        scores[y]=scores[y]+1; // Candidate gets one point if the score is above average for this user
      }
    }
  }

  log('veam final scores: '+scores);

  return scores;
}

function mbr(candidates, ratingMatrix, weights)
{
  log('mbr candidates:');
  log(candidates);

  var medians=[];
  for(var y=0; y<candidates.length; y++) // Add scores for each candidate
  {
    var scores=[];
    for(var x=0; x<ratingMatrix[candidates[y]].length; x++) // Add scores for each candidate
    {
      if(ratingMatrix[candidates[y]][x]!='nr')
      {
        scores.push(ratingMatrix[candidates[y]][x]*weights[candidates[y]]);
      }
    }

    if(scores.length>0)
    {
      scores.sort(function(a,b){return a - b});

      log("mbr scores:");
      log(scores);

      var middle = Math.floor(scores.length / 2);
      if ((scores.length % 2) != 0)
      {
        medians.push(scores[middle]);
      }
      else
      {
        medians.push((scores[middle - 1] + scores[middle]) / 2);
      }
    }
  }

  log('medians:');
  log(medians);

  return medians;
}

function reweight(weights, winners, ratingMatrix)
{
  var C=5;
  for(var i=0; i<weights.length; i++) // Score candidate with the current winner set and weightings
  {
    var winnerScores=[];
    for(var j=0; j<winners.length; j++)
    {
      winnerScores.push(ratingMatrix[j][i]); // Collect score of winner j by voter i
    }

    weights[i]=C/(C+sum(winnerScores));
  }

  return weights;
}

function addWinner(winners, weights, ratingMatrix, vetoList)
{
    var scores=[];
    for(var i=0; i<ratingMatrix.length; i++) // Score candidate with the current winner set and weightings
    {
      if(i in oc(winners) || i in oc(vetoList))
      {
        scores.push('nr');
      }
      else
      {
        scores.push(sum(ratingMatrix[i])*weights[i]);
      }
    }

    log('scores: '+scores);
    var winner=maxpos(scores);
    if(winner.length==0)
    {
      log('no winner: '+scores);
    }
    else if(winner.length==1)
    {
      log('winner: '+winner[0]);
      winners.push(winner[0]);
    }
    else
    {
      log('tie: '+winner.length);
      var veams=veam(winner, ratingMatrix, weights);
      var veamWinner=maxpos(veams);
      if(veamWinner.length==0)
      {
        log('no veam winner');
      }
      else if(veamWinner.length==1)
      {
        log('veam winner: '+veamWinner[0]);
        winners.push(winner[veamWinner[0]]);
      }
      else
      {
        log('veam tie!');
        var mbrs=mbr(winner, ratingMatrix);
        var mbrWinner=maxpos(mbrs);
        if(mbrWinner.length==0)
        {
          log('no veam winner');
        }
        else if(mbrWinner.length==1)
        {
          log('mbr winner: '+mbrWinner[0]+' -> '+winner[mbrWinner[0]]);
          winners.push(winner[mbrWinner[0]]);
        }
        else
        {
          log('mbr tie!');
          log('ranking in listed order, totally arbitrary');
          for(var i=0; i<winner.length; i++)
          {
            winners.push(winner[i]);
          }
        }
      }
    }
}

function updateResults()
{
  log('updating results');
  var newState=wave.getState();

  var amax=0;
  var optimal=[];
  var allEntries=[];
  var rcmax=0;

  var ratingMatrix=[];
  var optionsCount=$("#resultDates tr").size();
  var vetoList=[];
  var quorumList=[];

  var keys = newState.getKeys();
  $("#resultDates tr").each(function(index, item) {
    var date=$(item).children(".date").text();
    var twin=$("#"+encodeToHex(date));
    var matrixEntry=$('[date="'+date+'"]');
    var actd=$(item).children(".available");
    var rvtd=$(item).children(".ratings");
    var vartd=$(item).children(".variance");
    var qtd=$(item).children(".quorum");
    var vctd=$(item).children(".vetos");
    var rltd=$(item).children(".reasons");
    log(date);
    var ac=0;
    var samples=[];
    var vc=0;
    var rl=[];

    var ratingRow=[];
    ratingMatrix.push(ratingRow);

    for (var i = 0; i < keys.length; ++i)
    {
      var user = keys[i];
      var userState=JSON.parse(newState.get(user));

      var userAttending=getValue(userState, 'attending', false);
      if(userAttending)
      {
        var userAvailable=getValue(userState, 'available', {});
        var userRatings=getValue(userState, 'ratings', {});
        var userVetos=getValue(userState, 'vetos', {});
        var userReasons=getValue(userState, 'reasons', {});

        if(getValue(userAvailable, date, false))
        {
          ac=ac+1;
        }

        ur=getValue(userRatings, date, 'nr');
        if(ur!='nr')
        {
          samples.push(parseInt(ur));
          ratingRow.push(parseInt(ur));
        }
        else
        {
          ratingRow.push('nr');
        }

        if(getValue(userVetos, date, false))
        {
          vc=vc+1;
          ures=getValue(userReasons, date, '');
          if(ures!='')
          {
            rl.push(ures);
          }
        }
      }
      else
      {
        for(var x=0; x<optionsCount; x++)
        {
          ratingRow.push('nr');
        }
      }
    }

    var entry=[];
    entry.push(date);
    entry.push(ac);

    if(ac>amax)
    {
      amax=ac;
    }
    actd.text(ac);
//    rctd.text(samples.length);

    if(samples.length==0)
    {
      rvtd.text('NR');
      entry.push(0);
      vartd.text('NR');
      entry.push(0);
    }
    else
    {
      var rv=(Math.round(average(samples)*10)/10);
      if(rv>rmax)
      {
        rmax=rv;
      }
      entry.push(rv);
      rvtd.text(rv);

      var varv=(Math.round(variance(samples)*10)/10);
      if(varv>vmax)
      {
        vmax=varv;
      }
      entry.push(varv);
      vartd.text(varv);
    }

    entry.push(samples.length);

    allEntries.push(entry);

    if(vc==0)
    {
      optimal.push(entry);

      if(samples.length>rcmax)
      {
        rcmax=samples.length;
      }
    }
    else
    {
      qtd.text('N/A')
      vetoList.push(index);
    }

    vctd.text(vc);

    if(rl.length==0)
    {
      s='&nbsp;';
    }
    else
    {
      s='<select>';
      for(var x=0; x<rl.length; x++)
      {
        s=s+'<option>'+rl[x]+'</option>';
      }
      s=s+'</select>';
    }

    rltd.empty().append(s);

    if(vc>0)
    {
      $(item).addClass('vetoed');
      $(twin).addClass('vetoed');
      $(matrixEntry).addClass('vetoed');
    }
    else
    {
      $(item).removeClass('vetoed');
      $(twin).removeClass('vetoed');
      $(matrixEntry).removeClass('vetoed');
    }
  });

  log('rcmax: '+rcmax);
  log('allEntries:');
  log(allEntries);

  for(var x=0; x<allEntries.length; x++)
  {
    var entry=allEntries[x];
    var date=entry[0];

    var rc=entry[4];
    if(rc>=(rcmax/2))
    {
      $("#result-"+encodeToHex(date)).children(".quorum").text('Yes');
      quorumList.push(x);
    }
    else
    {
      $("#result-"+encodeToHex(date)).children(".quorum").text('No');

      for(var y=0; y<ratingMatrix[x].length; y++)
      {
        ratingMatrix[x][y]='nr';
      }
    }
  }

  log('quorumList:');
  log(quorumList);

  if(showVetoedDates)
  {
    showVetoed();
  }
  else
  {
    hideVetoed();
  }

  $("#resultDates tr td").removeClass('optimal');

  log(optimal);

  var o1=[];
  var o2=[];
  var o3=[];

  var rmax=0;
  var vmax=0;

  var rrvs=[];

  for(var x=0; x<optimal.length; x++)
  {
    var entry=optimal[x];
    var date=entry[0];
    var ac=entry[1];
    var rv=entry[2];

    var rc=entry[4];
    if(ac==amax)
    {
      o1.push(entry);
      log($("#result-"+encodeToHex(date)).children(".available"));
      $("#result-"+encodeToHex(date)).children(".available").addClass('optimal');

      if(rv>rmax)
      {
        rmax=rv;
      }
    }
  }

  log(o1);

  for(var x=0; x<o1.length; x++)
  {
    var entry=o1[x];
    var date=entry[0];

    var rv=entry[2];
    var varv=entry[3];
    if(rv==rmax)
    {
      o2.push(entry);
      $("#result-"+encodeToHex(date)).children(".ratings").addClass('optimal');
      $("#result-"+encodeToHex(date)).children(".date").addClass('optimal');

      if(varv>vmax)
      {
        vmax=varv;
      }
    }
  }

  log(o2);

  for(var x=0; x<o2.length; x++)
  {
    var entry=o2[x];
    var date=entry[0];


    var varv=entry[3];
    if(varv==vmax)
    {
      o3.push(entry);
      $("#result-"+encodeToHex(date)).children(".variance").addClass('optimal');
    }
  }

  log(o3);

  var weights=[];
  for (var x=0; x < ratingMatrix[0].length; x++)
  {
    weights.push(1);
  }

  var ranking=[];
  for(var x=0; x<ratingMatrix.length; x++) // Loop once per candidate, so we get a ranking for each candidate
  {
    addWinner(ranking, weights, ratingMatrix, vetoList);
    log('ranking: '+ranking);
  }
  log('final ranking: '+ranking);

  var winners=[];
  for(var x=0; x<ratingMatrix.length; x++) // Loop once per candidate, so we get a ranking for each candidate
  {
    addWinner(winners, weights, ratingMatrix, vetoList);
    log('winners: '+winners);
    log('weights: '+weights);
    weights=reweight(weights, winners, ratingMatrix);
  }
  log('final winners: '+winners);

  $("#resultDates tr").each(function(index, item) {
    if(index in oc(vetoList) || !(index in oc(quorumList)))
    {
      $(item).children(".ranking").text('N/A');
      $(item).children(".rrv").text('N/A');
    }
    else
    {
      var rank=ranking.findIndex(index)+1;
      $(item).children(".ranking").text(rank);

      if(rank==1)
      {
        $(item).children(".ranking").addClass('optimal');
      }

      var rrv=winners.findIndex(index)+1;
      $(item).children(".rrv").text(rrv);

      if(rrv==1)
      {
        $(item).children(".rrv").addClass('optimal');
      }
    }
  });
}

function updateMatrix()
{
  log('updating matrix');
  var newState=wave.getState();

  $("#matrixHeader").empty().append("<th>&nbsp;</th>");
  for(var x=0; x<knownDates.length; x++)
  {
    $("#matrixHeader").append('<th date="'+knownDates[x]+'">'+knownDates[x]+'</th>');
  }

  $("#matrixEntries").empty();
  var keys = newState.getKeys();
  for(var x=0; x<keys.length; x++)
  {
    log(keys[x]);
    var user=wave.getParticipantById(keys[x]);
    if(user!==undefined)
    {
      log(user);
      var userState=JSON.parse(newState.get(keys[x]));

      var userAttending=getValue(userState, 'attending', false);
      if(userAttending)
      {
        var s="<tr><td>"+user.getDisplayName()+"</td>";
        for(var y=0; y<knownDates.length; y++)
        {
          var userAvailable=getValue(userState, 'available', {});
          var av=getValue(userAvailable, knownDates[y], false);
          if(av)
          {
            s=s+'<td class="yes" date="'+knownDates[y]+'">&#x2713;</td>';
          }
          else
          {
            s=s+'<td class="no" date="'+knownDates[y]+'">&nbsp;</td>';
          }
        }

        s=s+"</tr>";
        $("#matrixEntries").append(s);
      }
    }
  }
}

function updateSettings()
{
  var newState=wave.getState();

  var settings=JSON.parse(newState.get('settings'));
  var pt=getValue(settings, 'participating', 'Participating');
  if(pt=='')
  {
    pt='Participating';
  }

  $("#participatingText").val(pt);
  $("#participating").text(pt);
  $("#notparticipating").text('Not '+pt);

  var at=getValue(settings, 'approval', '');
  if(at=='')
  {
    at='Approve';
  }

  $("#approvalText").val(at);
  $(".approve").text(at);

  var abt=getValue(settings, 'addButton', '');
  if(abt=='')
  {
    abt='Option';
  }

  $("#addButtonText").val(abt);
  $(".option").text(abt);
  $("#addDate").attr("value", "Add "+abt);
}

function submitDate(date)
{
  var viewer=wave.getViewer().getId();
  var state=wave.getState();

  var myState=JSON.parse(state.get(viewer, "{}"));

  var dates=myState['dates'];
  if(dates==null)
  {
    dates=[];
  }
  dates.push(date);

  myState['dates']=dates;

  var delta={};
  delta[viewer]=JSON.stringify(myState);

  state.submitDelta(delta);

  log('changed');
  log(JSON.stringify(delta));
}

function geekOut()
{
  geekout=true;
  $(".geekout").show();
  return false;
}

function showVetoed()
{
  showVetoedDates=true;
  $("#showVetoed").hide();
  $("#hideVetoed").show();
  $("#dates .vetoed").show();
  $("#matrixHeader .vetoed").show();
  $("#matrixEntries .vetoed").show();
  return false;
}

function hideVetoed()
{
  showVetoedDates=false;
  $("#showVetoed").show();
  $("#hideVetoed").hide();
  $("#dates .vetoed").hide();
  $("#matrixHeader .vetoed").hide();
  $("#matrixEntries .vetoed").hide();
  return false;
}

function saveSettings()
{
  log('saving settings');

  var pt=$("#participatingText").val();
  var at=$("#approvalText").val();
  var abt=$("#addButtonText").val();

  var viewer=wave.getViewer().getId();
  var state=wave.getState();

  var settings=JSON.parse(state.get('settings', "{}"));

  if(pt!=null && pt!='')
  {
    settings['participating']=pt;
  }
  if(at!=null && at!='')
  {
    settings['approval']=at;
  }
  if(abt!=null && abt!='')
  {
    settings['addButton']=abt;
  }

  var delta={};
  delta['settings']=JSON.stringify(settings);

  state.submitDelta(delta);

  log('changed');
  log(delta);

  return false;
}

function partyoclockInit()
{
  $("#boardContainer").tabs();
  $(".available").click(checkAvailable);
  $("#entryTemplate").hide();
  $(".available").select(checkAvailable);
  $(".rating").click(checkRatings);
  $(".veto").click(checkVetos);
  $(".reason").blur(checkReasons);
  $(".ana").click(checkAttending);
  $("#addDate").click(addDate);
  $(".geekout").hide();
  $("#geekoutButton").click(geekOut);
  $("#showVetoed").click(showVetoed);
  $("#hideVetoed").click(hideVetoed);
  hideVetoed();

  $("#saveSettings").click(saveSettings);
}

function init()
{
  partyoclockInit();
  waveInit();
}

$(document).ready(init());

